/***************************************************************************
 *  Filename: communicationhandler.cpp
 *  Class: CommunicationHandler
 *
 *  Copyright 2012  Jacco van der Spek
 *  <jaccovdspek@gmail.com>
 *
 *  Copyright 2012  Mario Henrique Voorsluys
 *  <forcaeluz@gmail.com>
 *
 ****************************************************************************/

/*
 *
 * This file is part of %ProjectName%.
 *
 *    %ProjectName% is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    %ProjectName% is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with %ProjectName%.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "communicationhandler.h"


#include "communicationhandler.h"
#include <QDebug>
#include <QStringList>


CommunicationHandler::CommunicationHandler(bool raw, QObject *parent) :
    QObject(parent)
{
    serial = new QextSerialPort();
    rawData = raw;
    if(!rawData)
        connect(serial, SIGNAL(readyRead()), this, SLOT(getByte()));
    else
        connect(serial, SIGNAL(readyRead()), this, SIGNAL(byteAvailable()));
}

void CommunicationHandler::send(int count, char *bytes)
{
    serial->write(bytes,count);
    serial->flush();
}

int CommunicationHandler::receive(int count, char *bytes)
{
    return serial->read(bytes, count);
}

void CommunicationHandler::setupPort(QString portname, BaudRateType baudrate, DataBitsType databits,
                                     ParityType parity, FlowType flowctrl, StopBitsType stopbits)
{
    serial->close();
    serial->setPortName(portname);
    serial->setBaudRate(baudrate);
    serial->setQueryMode(QextSerialPort::EventDriven);
    serial->setDataBits(databits);    // DATA_8
    serial->setParity(parity);    // PAR_NONE
    serial->setFlowControl(flowctrl);  // CHANGE TO FLOW_HARDWARE  / FLOW_OFF
    serial->setStopBits(stopbits);    // CHANGE TO STOP_2 / STOP_1
    serial->setTimeout(100);
    if(serial->open(QIODevice::ReadWrite | QIODevice::Unbuffered))
    {
        qDebug() << "Succesfully opened serial port" << portname;

    }else{
        qWarning() << "Failed to open port: " << portname;
        qWarning() << "Error: " << serial->errorString();
    }
}

void CommunicationHandler::sendToPort(QByteArray bytes)
{
    send(bytes.size(),bytes.data());
}

QString CommunicationHandler::receiveFromPort()
{
    QString message;
    char buffer[2];
    int rec = receive(1,buffer);
    buffer[rec]='\0';
    message.append(buffer);
    return message;
}

QByteArray CommunicationHandler::receiveRawFromPort(int length){
    QByteArray rawData;

    if(length==-1){
        char buffer[256];
        int rec = receive(256, buffer);
        rawData.append(QByteArray::fromRawData(buffer, rec));
    }else{
        char buffer[length];
        while(length > 0){
            int rec = receive(length, buffer);
            rawData.append(QByteArray::fromRawData(buffer, rec));
            length -= rec;
        }
    }
    return rawData;
}

QString CommunicationHandler::readLine(){
    if(!rawData){
        QString message;
        message = buffer;
        QStringList lines = message.split('\n');
        buffer.remove(0, lines.at(0).size()+1);
        qDebug() << "[CommunicationHandler] Buffer after read line is: " << buffer;
        return lines.at(0);
    }else{
        qWarning() << "[CommunicationHandler] Read line called in raw data mode. Are you sure??";
        return "";
    }
}

void CommunicationHandler::closePort()
{
    serial->close();
}

bool CommunicationHandler::checkPort()
{
    if(serial->bytesAvailable()>0)
        return true;
    else
        return false;
}

void CommunicationHandler::getByte(){
    QByteArray tmp = serial->readAll();
    if(buffer.contains('\n')){
        emit(newLineReady());
    }
    buffer.append(tmp);
    qDebug() << "[CommunicationHandler] Buffer after getByte is" << buffer;
}
